String Processing Utilities

Leftmost and rightmost strings

These utilities extract the N leftmost or rightmost characters.
// Leftmost characters
function leftmost(aString, aNum)
{
    var tmp = ""+aString

    if (aNum > tmp.length) return tmp
    return (tmp.substring(0, aNum))
}

// Rightmost characters
function rightmost(aString, aNum)
{
    var tmp = ""+aString
    if (aNum > tmp.length) return tmp
    return (tmp.substring(tmp.length - aNum, tmp.length))
}

Chopping substrings

These utilities search for a substring and chop at the beginning or the end of that string.

// Search for a substring and chop before it
function chopit(aString, aSubstring)
{
    var tmp = ""+aString
    if (tmp.length == 0) return tmp
    if (aSubstring.length == 0) return tmp

	var where
    if ((where = tmp.indexOf(aSubstring)) < 0) return tmp
    return (tmp.substring(0, where))
}

// Search for a substring and lop off everything after it
function lopit(aString, aSubstring)
{
    var tmp = ""+aString
    if (tmp.length == 0) return tmp
    if (aSubstring.length == 0) return tmp

	var where
    if ((where = tmp.indexOf(aSubstring)) < 0) return tmp
    return (tmp.substring(where+aSubstring.length, tmp.length))
}

Stripping strings

This utility strips blanks from the front and back of a string.

// Strips a string of blanks on either end
function stripBlanks(aString)
{
    var tmp = ""+aString
    var bottom = 0
    var top = tmp.length
    
    if (tmp == "") return tmp
    
    while (tmp.substring(bottom, bottom + 1) == " ") bottom++
    if (bottom >= top) return("")
    
    while (tmp.substring(top - 1, top) == " ") top -= 1
    
    return tmp.substring(bottom, top)
}

Reversing strings

This utility reverses a string.

// Reverse a String
function reverse(aString)
{
    var tmp = ""+aString
    var result = ""

    for (var i = tmp.length; i >= 0; i -= 1) 
    	result += tmp.substring(i, i + 1)
    
    return result
}

Creating repeating blank and character strings

These utilities extract create repeated sequences of blanks or characters. (Note: The blank string will be compressed by HTML when it shows the result, but the string has been correctly created, as the length shows.)
// Create a blank string with minimum number of string clones
function blankstr(aNum)
{
    var tmp = ""
    
    var blank10 = "          " // 10 space long constant
    
    var tens = Math.floor(aNum / 10) // how many 10s
    var units = aNum % 10            // how many 1s
    
    // Add in the blanks
    for (var i = 0; i < tens; i++) tmp += blank10
    for (var i = 0; i < units; i++) tmp += " "
    
    return tmp
}


// Create a string with a repeated sequence of characters
function seqstr(aString, aNum)
{
    var tmp = ""+aString
    var seq = ""
    for (var i = 0; i < aNum; i++) seq += tmp
    return seq
}

Copyright ©1998 by Charles River Media, All Rights Reserved